$(function() {
  class UpdatePassword {
    constructor() {
      this.init();
    }
    init() {
      //获取用户id 和 token
      this.id = cookie('id') ? cookie('id') : null;
      this.token = cookie('token') ? cookie('token') : null;
      this.isLogin();
      this.initDom();
      this.bindEvent();
    }
    initDom() {
      //获取旧密码
      this.old_password = $('#oldPassword');
      //获取新密码
      this.new_password = $('#newPassword');
      //获取确定新密码
      this.rnew_password = $('#rNewPassword');
      //获取提交按钮
      this.update = $('#update_btn');
    }
    bindEvent() {
      this.update.on('click', async() => {
        let res = await this.sendUpdatePassword();
        if(res.data.code === 1) {
          cookie('id', null);
          cookie('token', null);
          new Toast({
            message: res.data.message,
            color: '#67C23A',
            callback() {
              location.href = './login.html';
            }
          });
        }else {
          new Toast({
            message: '表单信息有误,请重新检查输入',
            color: '#F56C6C'
          });
        }
      })
    }
    //发送修改密码请求
    sendUpdatePassword() {
      return axios({
        url: 'http://127.0.0.1:8888/users/rpwd',
        method: 'POST',
        data: formData({
          id: this.id,
          oldPassword: this.old_password.val(),
          newPassword: this.new_password.val(),
          rNewPassword: this.rnew_password.val()
        }),
        headers: {
          Authorization: this.token
        }
      });
    }
    //判断用户是否登陆
    isLogin() {
      if(!(this.id && this.token)) {
        new Toast({
          message: '用户未登陆或认证已过期，请您登录后再进行操作',
          color: '#E6A23C',
          callback() {
            location.href = './login.html';
          }
        });
      }
    }
  }
  new UpdatePassword();
})